<?php
/**********************************************************************************
WIKINDX: Bibliographic Management system.
Copyright (C)

This program is free software; you can redistribute it and/or modify it under the terms 
of the GNU General Public License as published by the Free Software Foundation; either 
version 2 of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; 
without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. 
See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License along with this program; 
if not, write to the 
Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA

The WIKINDX Team 2006
sirfragalot@users.sourceforge.net
**********************************************************************************/
/*****
*	Group class.
*
*	$Header: /cvsroot/wikindx/wikindx3/core/group/GROUP.php,v 1.13 2006/10/06 07:52:58 sirfragalot Exp $
*****/
class GROUP
{
// Constructor
	function GROUP($db)
	{
		$this->db = $db;
	}
// Get category names from WKX_category.  Return associative array of id => category.
	function grabAll()
	{
		include_once("core/html/HTML.php");
		$html = new HTML();
		include_once("core/messages/MESSAGES.php");
		$messages = new MESSAGES();
		$recordset = $this->db->select(array("WKX_category"), array("id", "category"), 
			'ORDER BY ' . $this->db->tidyInputClause('category'));
		while($row = $this->db->loopRecordSet($recordset))
			$groups[$row['id']] = $html->dbToFormTidy($row['category']);
		if(isset($groups))
		{
// $groups[1] is hard-wired to 'General' in the database -- for display, change it to the required localization
			$groups[1] = $messages->text('resources', 'general');
			return $groups;
		}
// shouldn't ever happen since 1 => 'General' should always be set.
		return FALSE;
	}
// Get category names from WKX_category.  Return associative array of id => category.  Only return categories for resources in which there is metadata.
	function grabMeta()
	{
		include_once("core/html/HTML.php");
		$html = new HTML();
// quotes
		$recordset = $this->db->select(array("WKX_resource", "WKX_resource_quote"), 
		array("WKX_category.id", "category"), 
			" LEFT JOIN " . $this->db->formatfield('WKX_resource_category') . 
				" ON " . $this->db->formatfield('WKX_resource_category.id') . 
				" = " . $this->db->formatfield('WKX_resource.id') .  
			" LEFT JOIN " . $this->db->formatfield('WKX_category') . 
				" ON FIND_IN_SET(" . 
				$this->db->formatfield('WKX_category.id') . ", CONCAT(" . 
				$this->db->formatfield('WKX_resource_category.categories') . ", ','))" . 
			" WHERE " .  $this->db->formatfield('WKX_resource_quote.resourceId') . 
				" = " . $this->db->formatfield('WKX_resource.id') .  
			" ORDER BY " . $this->db->tidyInputClause('category'));
		while($row = $this->db->loopRecordSet($recordset))
			$groups[$row['id']] = $html->dbToFormTidy($row['category']);
// paraphrases
		$recordset = $this->db->select(array("WKX_resource", "WKX_resource_paraphrase"), 
		array("WKX_category.id", "category"), 
			" LEFT JOIN " . $this->db->formatfield('WKX_resource_category') . 
				" ON " . $this->db->formatfield('WKX_resource_category.id') . 
				" = " . $this->db->formatfield('WKX_resource.id') .  
			" LEFT JOIN " . $this->db->formatfield('WKX_category') . 
				" ON FIND_IN_SET(" . 
				$this->db->formatfield('WKX_category.id') . ", CONCAT(" . 
				$this->db->formatfield('WKX_resource_category.categories') . ", ','))" . 
			" WHERE " .  $this->db->formatfield('WKX_resource_paraphrase.resourceId') . 
				" = " . $this->db->formatfield('WKX_resource.id') .  
			" ORDER BY " . $this->db->tidyInputClause('category'));
		while($row = $this->db->loopRecordSet($recordset))
			$groups[$row['id']] = $html->dbToFormTidy($row['category']);
// musings
		$recordset = $this->db->select(array("WKX_resource", "WKX_resource_musing"), 
		array("WKX_category.id", "category"), 
			" LEFT JOIN " . $this->db->formatfield('WKX_resource_category') . 
				" ON " . $this->db->formatfield('WKX_resource_category.id') . 
				" = " . $this->db->formatfield('WKX_resource.id') .  
			" LEFT JOIN " . $this->db->formatfield('WKX_category') . 
				" ON FIND_IN_SET(" . 
				$this->db->formatfield('WKX_category.id') . ", CONCAT(" . 
				$this->db->formatfield('WKX_resource_category.categories') . ", ','))" . 
			" WHERE " .  $this->db->formatfield('WKX_resource_musing.resourceId') . 
				" = " . $this->db->formatfield('WKX_resource.id') .  
			" ORDER BY " . $this->db->tidyInputClause('category'));
		while($row = $this->db->loopRecordSet($recordset))
			$groups[$row['id']] = $html->dbToFormTidy($row['category']);
		if(isset($groups))
			return $groups;
// shouldn't ever happen since 1 => 'General' should always be set.
		return FALSE;
	}
// return a SQL condition clause when selecting by category
	function selectCondition($input)
	{
		$condition = '';
		$selectArray = explode(",", $input['category']);
// NB MySQL bug: http://bugs.mysql.com/bug.php?id=2047 -- append comma temporarily
		foreach($selectArray as $key => $value)
			$conditionArray[] = "FIND_IN_SET(" . $this->db->tidyInput($value) . ", CONCAT(" . 
			$this->db->formatfield('categories') . ", ','))";
		$condition .= implode(" " . $input['categoryMethod'] . " ", $conditionArray);
		return $condition;
	}
// Update $input to category table.  If category ID exists, update category name otherwise do nothing.
// $input is id => groupName
	function updateSql($input)
	{
		$recordset = $this->db->select(array("WKX_category"), array("id", "category"));
		while($row = $this->db->loopRecordSet($recordset))
		{
			if(array_key_exists($row['id'], $input))
			{
				$update['category'] = $input[$row['id']];
				$this->db->update('WKX_category', $update, 
				"WHERE " . $this->db->formatField('id') . "=" . $this->db->tidyInput($row['id']));
				unset($input[$row['id']]);
			}
		}
		return TRUE;
	}
// Add a new category to the category table
	function addSql($category)
	{
// database match is case insensitive.
		$recordset = $this->db->select(array("WKX_category"), array("id"), 
			"WHERE " . $this->db->formatField('category') . "=" . $this->db->tidyInput($category));
// If category already exists quietly return without error.
		if($id = $this->db->fetchOne($recordset))
			return $id;
		$this->db->insert("WKX_category", array('category'), array($category));
		return TRUE;
	}
// Delete category(s) from category table.  $input is array of ids in WKX_category.
// 'General' category always has id 1.
	function deleteSql($input)
	{
// Grab info from WKX_resource_category table and store those resources that require updating.....
		$condition = " WHERE ";
// NB MySQL bug: http://bugs.mysql.com/bug.php?id=2047 -- append comma temporarily
		foreach($input as $value)
			$conditionArray[] = "FIND_IN_SET(" . $this->db->tidyInput($value) . ", CONCAT(" . 
			$this->db->formatField('categories') . ", ','))";
		$condition .= implode(" OR ", $conditionArray);
		$recordset = $this->db->select(array("WKX_resource_category"), array("id", "categories"), $condition);
		while($row = $this->db->loopRecordSet($recordset))
		{
			$list = explode(",", $row['categories']);
// In the comma-delimited list of $input, exists a deleted category?  If so, update with reduced category list
			foreach($input as $value)
			{
				if(($key = array_search($value, $list)) !== FALSE)
					unset($list[$key]);
			}
// just in case... set to 'General' category
			if(empty($list))
				$list[] = 1;
			$list = implode(",", $list);
			$this->db->update('WKX_resource_category', array("categories" => $list), 
				"WHERE " . $this->db->formatfield('id') . "=" . $this->db->tidyInput($row['id']));
		}
// Finally delete categories and optimize table
		foreach($input as $value)
			$this->db->delete('WKX_category', "WHERE " . $this->db->formatfield('id') . "=" . 
				$this->db->tidyInput($value));
		$this->db->optimize('WKX_category');
		return TRUE;
	}
// return link to other resources in this resource's categories or just the plain category if no other resources found.
	function getCategoryLink($resourceId, $cId, $category)
	{
		include_once("core/session/SESSION.php");
		$session = new SESSION();
		$sql = $this->db->selectNoExecute(
			array("WKX_resource"), array(array("WKX_resource.id" => "resourceId")), 
			" LEFT JOIN " . 
				$this->db->formatTable("WKX_resource_category") . " ON " . 
				$this->db->formatField("WKX_resource.id") . "=" . 
				$this->db->formatField("WKX_resource_category.id") .  
// NB MySQL bug: http://bugs.mysql.com/bug.php?id=2047 -- append comma temporarily
			" WHERE FIND_IN_SET(" . $this->db->tidyInput($cId) . ", CONCAT(" . 
				$this->db->formatField('categories') . ", ','))"
			);
// If we are browsing a user bibliography, we return only results from this bibliography
		if($useBib = $session->getVar("mywikindx_bibliography_use"))
		{
			if($this->userBibCategories($sql, $resourceId, $useBib))
				return MISC::a("link", $category, "index.php?action=listCategoryProcess" . 
					htmlentities("&id=" . $cId));
			else
				return $category;
		}
// Results from the Master Bibliography
		$masterSql = $sql . " AND (" . $this->db->formatField('WKX_resource.id') . " != " . 
			$this->db->tidyInput($resourceId) . ")";
		$recordset = $this->db->query($masterSql);
		while($line = $this->db->loopRecordSet($recordset))
			$masterCategoryResources[] = $line['resourceId'];
		if(isset($masterCategoryResources))
			return MISC::a("link", $category, "index.php?action=listCategoryProcess" . 
				htmlentities("&id=" . $cId));
		else
			return $category;
	}
// Scan user bibliography for categories
	function userBibCategories($sql, $resourceId, $useBib)
	{
		$recordset = $this->db->select(array('WKX_user_bibliography'), array('bibliography'), 
			" WHERE " . $this->db->formatfield('id') . "=" . $this->db->tidyInput($useBib));
		$dbBibs = $this->db->fetchOne($recordset);
		$bibsArray = explode(",", $dbBibs);
		$bibCondition = "(" . $this->db->formatfield('WKX_resource.id') . " = ";
		foreach($bibsArray as $id)
		{
			if($id == $resourceId)
				continue;
			$conditionArray[] = $this->db->tidyInput($id);
		}
		if(!isset($conditionArray))
			return FALSE;
		$bibCondition .= implode(" OR " . $this->db->formatfield('WKX_resource.id') . " = ", 
			$conditionArray) . ")";
		$sql .= " AND " . $bibCondition;
		$recordset = $this->db->query($sql);
		while($line = $this->db->loopRecordSet($recordset))
			$bibCategoryResources[] = $line['resourceId'];
		if(isset($bibCategoryResources))
			return $bibCategoryResources;
	}
}
?>
